package com.base.thread.demo_45;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 *  使用 ForkJoin 框架 来计算1-100的和
 *  把任务拆分成每2个数相加
 * @ClassName: Demo
 * @Description: 
 * @Author xuyou
 * @DateTime 2020年12月18日 上午10:38:20
 */
public class Demo extends RecursiveTask<Integer> {

	private int begin;
	private int end;

	public Demo(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		System.out.println(Thread.currentThread().getName() + " ... " + "begin: "+ begin + " end: " + end );
		
		int sum = 0;
		// 拆分任务
		if (end - begin <= 2) {
			// 计算
			for (int i = begin; i <= end ; i++) {
				sum += i;
			}
		}else {
			// 拆分
			Demo d1 = new Demo(begin, (begin + end) / 2);
			Demo d2 = new Demo((begin + end) / 2 + 1, end);
			
			// 执行任务
			d1.fork();
			d2.fork();
			
			Integer a = d1.join();
			Integer b = d2.join();
			
			System.out.println("a: "+ a + ",b: " + b);
			sum = a+b;
		
		}
		return sum;
	}

	public static void main(String[] args) throws Exception, Exception {
		
		ForkJoinPool pool = new ForkJoinPool();
		
		Future<Integer> task = pool.submit(new Demo(1, 100));
		
		System.out.println("去干其他的事情。。。。。。。。。。。");
		
		System.out.println("计算的值为: " + task.get());
	}
	
}
